package com.vilynn.interview.nowcoder;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;

public class NC24 {

    public class ListNode {
        int val;
        ListNode next = null;
    }

    public ListNode deleteDuplicates(ListNode head) {
        // write code here
        Map<Integer, HashSet<ListNode>> map = new LinkedHashMap<>();
        while (head != null) {
            ListNode next = head;

            map.computeIfAbsent(next.val, o -> new HashSet<ListNode>()).add(next);

            head = head.next;
        }

        ListNode res = null;
        ListNode temp = null;
        for (Map.Entry<Integer, HashSet<ListNode>> entry : map.entrySet()) {
            HashSet<ListNode> value = entry.getValue();
            Integer key = entry.getKey();

            if (value.size() > 1) {
                continue;
            }
            if (res == null) {
                res = new ListNode();
                res.val = key;
                temp = res;
            } else {
                ListNode nex = new ListNode();
                nex.val = key;
                temp.next = nex;

                temp = nex;
            }
        }
        return res;
    }

}
